/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.dao;

import han.bifang.common.entity.SoaStatService;
import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;
import han.bifang.common.persist.dao.DaoManager;
import han.bifang.common.persist.tx.Tx;
import han.bifang.common.persist.tx.TxManager;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class StatServiceDao {

	public static String createStatService(SoaStatService s)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			DaoManager.getDao().save(s);
			DaoManager.getDao().flush();
			tx.commit();
			return s.getId();
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(StatServiceDao.class);
			logger.error("StatServiceDao.createStatService()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"createStatService() error", e);
		} finally {
			tx.end();
		}
	}

	public static void modifyStatService(SoaStatService s)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			DaoManager.getDao().merge(s);
			DaoManager.getDao().flush();
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(StatServiceDao.class);
			logger.error("StatServiceDao.modifyStatService()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"modifyStatService() error", e);
		} finally {
			tx.end();
		}
	}

	public static SoaStatService getStatService(String serviceCode,
			String version) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaStatService s where s.serviceCode = ? and s.version = ?";
			List<SoaStatService> b = DaoManager.getDao().find(hql,
					new Object[] { serviceCode, version });
			tx.commit();
			if (b.size() == 0)
				return null;
			else
				return b.get(0);
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(StatServiceDao.class);
			logger.error("StatServiceDao.getStatService()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getStatService() error", e);
		} finally {
			tx.end();
		}
	}
	
	public static SoaStatService getStatService(String serviceCode) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaStatService s where s.serviceCode = ? ";
			List<SoaStatService> b = DaoManager.getDao().find(hql,
					serviceCode);
			tx.commit();
			if (b.size() == 0){
				SoaStatService s = new SoaStatService();
				s.setStatBeginTime(String.valueOf(System.currentTimeMillis()));
				return s;
			}
			SoaStatService s = new SoaStatService();
			s.setMaxResponseTime(0);
			s.setMinResponseTime(9999);
			s.setStatBeginTime(String.valueOf(System.currentTimeMillis()));
			
			for(SoaStatService ss : b){
				if(ss.getMaxResponseTime() > s.getMaxResponseTime()){
					s.setMaxResponseTime(ss.getMaxResponseTime());
				}
				if(ss.getMinResponseTime() < s.getMinResponseTime()){
					s.setMinResponseTime(ss.getMinResponseTime());
				}
				if(Long.parseLong(ss.getStatBeginTime()) - Long.parseLong(s.getStatBeginTime()) < 0){
					s.setStatBeginTime(ss.getStatBeginTime());
				}
				s.setSuccessRequest(s.getSuccessRequest() + ss.getSuccessRequest());
				s.setTotalRequest(s.getTotalRequest() + ss.getTotalRequest());
				s.setTotalResponseTime(s.getTotalResponseTime() + ss.getTotalResponseTime());
			}
			
			return s;
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(StatServiceDao.class);
			logger.error("StatServiceDao.getStatService()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getStatService() error", e);
		} finally {
			tx.end();
		}
	}

	public static void removeStatService(String serviceCode, String version)
			throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaStatService s where s.serviceCode = ? and s.version = ?";
			List<SoaStatService> b = DaoManager.getDao().find(hql,
					new Object[] { serviceCode, version });
			if (b.size() > 0) {
				DaoManager.getDao().delete(b.get(0));

				DaoManager.getDao().flush();
			}
			tx.commit();
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(StatServiceDao.class);
			logger.error("StatServiceDao.removeStatService()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"removeStatService() error", e);
		} finally {
			tx.end();
		}
	}

}
